package netty.pastePack;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import netty.pastePack.protocol.MessageProtocol;

import java.nio.charset.StandardCharsets;

/**
 * @Description TODO
 * @Author 李龙平
 * @Date 2020/10/13 17:45
 */
public class MyClentHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol msg) throws Exception {
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("客户端读取到了len" + len);
        System.out.println("客户端读的信息" + new String(content, StandardCharsets.UTF_8));
        System.out.println("客户端接收消息的次数：" + (++this.count));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 5; i++) {
            String msg = "今天难过了吗？";
            byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
            int len = bytes.length;
            MessageProtocol messageProtocol = new MessageProtocol();
            messageProtocol.setContent(bytes);
            messageProtocol.setLen(len);
            ctx.writeAndFlush(messageProtocol);
        }
    }


}
